import {
	getXcxOpenid,
	getMemberInfoByOpenId,
	createOrder,
	getSignupWeixin
} from '@/api'
import {
	baseUrl
} from './request'
import {
	reactive,
} from 'vue'
const wxUser = reactive({
	openId: "",
	phone: "",
	memberId: "",
	jwt: ''
})
export const wxOpenid = () => {

	return new Promise(async (resolve, reject) => {
		try {
			const user = uni.getStorageSync('wxuser')

			if (user) {
				wxUser.memberId = user.memberId
				wxUser.phone = user.phone
				wxUser.openId = user.openId
				wxUser.jwt = user.jwt
				resolve(wxUser)
				return false
			}
			let {
				code
			} = await wx.login();
			const res = await getXcxOpenid({
				code,
				
			})
			getUserInfo(res.data.openId, resolve)

		} catch (e) {
			console.log('Failed to fetch data:', e)
		}
	})

}
export const bindInvite = async(inviteOpenId)=>{
	console.log(inviteOpenId)
	let {
		code
	} = await wx.login();
	const res = await getXcxOpenid({
		code,
		inviteOpenId
	})
}
/** 根据openid 查询会员信息 */
const getUserInfo = async (openId, resolve) => {
	const res = await getMemberInfoByOpenId({
		openId
	})
	wxUser.memberId = res.result.id
	wxUser.phone = res.result.phone
	wxUser.jwt = res.result.jwt
	wxUser.openId = openId
	uni.setStorageSync('wxuser', wxUser)
	resolve(wxUser)

}

export const checkLogin = async (callback) => {
	const {
		phone
	} = await wxOpenid()
	if (!phone) {
		uni.navigateTo({
			url: '/pages/login/login'
		})
	} else {
		callback()
	}
}
export const sendCreateOrder = async (orderParams, orderToken) => {
	const order = await createOrder(orderParams, orderToken)
	const pay = await getSignupWeixin({
		orderId: order.result,
		payAmount: orderParams.payAmount,
		wxOpenId: orderParams.openId
	})
	uni.hideLoading()
	wx.requestPayment({
		timeStamp: pay.result.sdk_timestamp,
		nonceStr: pay.result.sdk_noncestr,
		package: pay.result.sdk_package,
		signType: pay.result.sdk_signtype,
		paySign: pay.result.sdk_paysign,
		success(res) {
			uni.navigateTo({
				url: '/pages/result/result?orderId=' + order.result+'&businessType='+orderParams.businessType
			})
		},
		fail(res) {
			uni.showToast({
				title: '支付取消',
				icon: "none"
			})
		}
	})
}
export const debounce = (func, wait) => {
	let timeout;
	return function() {
		const context = this,
			args = arguments;
		clearTimeout(timeout);
		timeout = setTimeout(() => {
			func.apply(context, args);
		}, wait);
	};
}

export const upload =  (callback) => {

	uni.chooseImage({
		count: 1, //默认9
		sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
		sourceType: ['album'], //从相册选择
		success:  (res)=> {
			wx.uploadFile({
				url: baseUrl + '/xcx/file/oss/upload', //仅为示例，非真实的接口地址
				filePath: res.tempFilePaths[0],
				name: 'file',
				success:(res) =>{
					const url = JSON.parse(res.data).data.url
					callback(url)
				}
			})
		}
	});
}